package cuiyt.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author cyt
 * @create 2020-09-16 上午 10:46
 */
public class demo3 {
    /**
     * 原子引用
     */
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("A1->" + stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("a1->" + atomicStampedReference.compareAndSet(1, 2, stamp, atomicStampedReference.getStamp() + 1));


            System.out.println("A2->" + atomicStampedReference.getStamp());

            System.out.println("a2->" + atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("A3->" + atomicStampedReference.getStamp());
        }, "a").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("B1->" + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("b1->" + atomicStampedReference.compareAndSet(1, 6, stamp, atomicStampedReference.getStamp() + 1));

            System.out.println("B2->" + atomicStampedReference.getStamp());

        }, "b").start();
    }
}
